home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / bin / pycompile < prev    next >
Encoding:
Text File  |  2012-05-04  |  12.5 KB  |  321 lines

  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # vim: et ts=4 sw=4
  4.  
  5. # Copyright ┬⌐ 2010 Piotr O┼╝arowski <piotr@debian.org>
  6. # Copyright ┬⌐ 2010 Canonical Ltd
  7. #
  8. # Permission is hereby granted, free of charge, to any person obtaining a copy
  9. # of this software and associated documentation files (the "Software"), to deal
  10. # in the Software without restriction, including without limitation the rights
  11. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. # copies of the Software, and to permit persons to whom the Software is
  13. # furnished to do so, subject to the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included in
  16. # all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. # THE SOFTWARE.
  25.  
  26. from __future__ import with_statement
  27. import logging
  28. import optparse
  29. import os
  30. import sys
  31. from os import environ, listdir, walk
  32. from os.path import abspath, exists, isdir, isfile, islink, join
  33. from subprocess import PIPE, STDOUT, Popen
  34. sys.path.insert(1, '/usr/share/python/')
  35. from debpython.version import SUPPORTED, debsorted, vrepr, \
  36.         get_requested_versions, parse_vrange, getver
  37. from debpython.option import Option, compile_regexpr
  38. from debpython.pydist import PUBLIC_DIR_RE
  39. from debpython.tools import memoize
  40.  
  41. # initialize script
  42. logging.basicConfig(format='%(levelname).1s: %(module)s:%(lineno)d: '
  43.                            '%(message)s')
  44. log = logging.getLogger(__name__)
  45. STDINS = {}
  46. WORKERS = {}
  47.  
  48. """TODO: move it to manpage
  49. Examples:
  50.     pycompile -p python-mako # package's public files
  51.     pycompile -p foo /usr/share/foo # package's private files
  52.     pycompile -p foo -V 2.6- /usr/share/foo # private files, Python >= 2.6
  53.     pycompile -V 2.6 /usr/lib/python2.6/dist-packages # python2.6 only
  54.     pycompile -V 2.6 /usr/lib/foo/bar.py # python2.6 only
  55. """
  56.  
  57.  
  58. ### FILES ######################################################
  59. def get_directory_files(dname):
  60.     """Generate *.py file names available in given directory."""
  61.     if isfile(dname) and dname.endswith('.py'):
  62.         yield dname
  63.     else:
  64.         for root, dirs, file_names in walk(abspath(dname)):
  65.             #if root != dname and not exists(join(root, '__init__.py')):
  66.             #    del dirs[:]
  67.             #    continue
  68.             for fn in file_names:
  69.                 if fn.endswith('.py'):
  70.                     yield join(root, fn)
  71.  
  72.  
  73. def get_package_files(package_name):
  74.     """Generate *.py file names available in given package."""
  75.     process = Popen("/usr/bin/dpkg -L %s" % package_name,\
  76.                     shell=True, stdout=PIPE)
  77.     stdout, stderr = process.communicate()
  78.     if process.returncode != 0:
  79.         log.error('cannot get content of %s', package_name)
  80.         exit(2)
  81.     for line in stdout.split('\n'):
  82.         if line.endswith('.py'):
  83.             yield line
  84.  
  85.  
  86. def get_private_files(files, dname):
  87.     """Generate *.py file names that match given directory."""
  88.     for fn in files:
  89.         if fn.startswith(dname):
  90.             yield fn
  91.  
  92.  
  93. def get_public_files(files, versions):
  94.     """Generate *.py file names that match given versions."""
  95.     versions_str = set("%d.%d" % i for i in versions)
  96.     for fn in files:
  97.         if fn.startswith('/usr/lib/python') and \
  98.            fn[15:18] in versions_str:
  99.             yield fn
  100.  
  101.  
  102. ### EXCLUDES ###################################################
  103. @memoize
  104. def get_exclude_patterns_from_dir(name='/usr/share/python/bcep/'):
  105.     """Return patterns for files that shouldn't be bytecompiled."""
  106.     if not isdir(name):
  107.         return []
  108.  
  109.     result = []
  110.     for fn in listdir(name):
  111.         with file(join(name, fn), 'r') as lines:
  112.             for line in lines:
  113.                 type_, vrange, dname, pattern = line.split('|', 3)
  114.                 vrange = parse_vrange(vrange)
  115.                 versions = get_requested_versions(vrange, available=True)
  116.                 if not versions:
  117.                     # pattern doesn't match installed Python versions
  118.                     continue
  119.                 pattern = pattern.rstrip('\n')
  120.                 if type_ == 're':
  121.                     pattern = compile_regexpr(None, None, pattern)
  122.                 result.append((type_, versions, dname, pattern))
  123.     return result
  124.  
  125.  
  126. def get_exclude_patterns(directory='/', patterns=None, versions=None):
  127.     """Return patterns for files that shouldn't be compiled in given dir."""
  128.     if patterns:
  129.         if versions is None:
  130.             versions = set(SUPPORTED)
  131.         patterns = [('re', versions, directory, i) for i in patterns]
  132.     else:
  133.         patterns = []
  134.  
  135.     for type_, vers, dname, pattern in get_exclude_patterns_from_dir():
  136.         # skip patterns that do not match requested directory
  137.         if not dname.startswith(directory[:len(dname)]):
  138.             continue
  139.         # skip patterns that do not match requested versions
  140.         if versions and not versions & vers:
  141.             continue
  142.         patterns.append((type_, vers, dname, pattern))
  143.     return patterns
  144.  
  145.  
  146. def filter_files(files, e_patterns, compile_versions):
  147.     """Generate (file, versions_to_compile) pairs."""
  148.     for fn in files:
  149.         valid_versions = set(compile_versions)  # all by default
  150.  
  151.         for type_, vers, dname, pattern in e_patterns:
  152.             if type_ == 'dir' and fn.startswith(dname):
  153.                 valid_versions = valid_versions - vers
  154.             elif type_ == 're' and pattern.match(fn):
  155.                 valid_versions = valid_versions - vers
  156.  
  157.             # move to the next file if all versions were removed
  158.             if not valid_versions:
  159.                 break
  160.         if valid_versions:
  161.             public_dir = PUBLIC_DIR_RE.match(fn)
  162.             if public_dir:
  163.                 yield fn, set([getver(public_dir.group(1))])
  164.             else:
  165.                 yield fn, valid_versions
  166.  
  167.  
  168. ### COMPILE ####################################################
  169. def py_compile(version, optimize, workers):
  170.     if not isinstance(version, basestring):
  171.         version = vrepr(version)
  172.     cmd = "/usr/bin/python%s%s -m py_compile -" \
  173.         % (version, '' if (__debug__ or not optimize) else ' -O')
  174.     process = Popen(cmd, bufsize=1, shell=True,
  175.                     stdin=PIPE, close_fds=True)
  176.     workers[version] = process  # keep the reference for .communicate()
  177.     stdin = process.stdin
  178.     while True:
  179.         filename = (yield)
  180.         stdin.write(filename + '\n')
  181.  
  182.  
  183. def compile(files, versions, force, optimize, e_patterns=None):
  184.     global STDINS, WORKERS
  185.     # start Python interpreters that will handle byte compilation
  186.     for version in versions:
  187.         if version not in STDINS:
  188.             coroutine = py_compile(version, optimize, WORKERS)
  189.             coroutine.next()
  190.             STDINS[version] = coroutine
  191.  
  192.     # byte compile files
  193.     for fn, versions_to_compile in filter_files(files, e_patterns, versions):
  194.         if not exists(fn):
  195.             # pycentral's cleanup-pkgprepare-updates hook will clean it later
  196.             if islink(fn):
  197.                 log.warn('dangling symlink skipped: %s (%s)', fn,
  198.                           os.readlink(fn))
  199.             continue
  200.         cfn = fn + 'c' if (__debug__ or not optimize) else 'o'
  201.         if exists(cfn) and not force:
  202.             ftime = os.stat(fn).st_mtime
  203.             try:
  204.                 ctime = os.stat(cfn).st_mtime
  205.             except os.error:
  206.                 ctime = 0
  207.             if (ctime > ftime):
  208.                 continue
  209.         for version in versions_to_compile:
  210.             try:
  211.                 pipe = STDINS[version]
  212.             except KeyError:
  213.                 # `pycompile /usr/lib/` invoked, add missing worker
  214.                 pipe = py_compile(version, optimize, WORKERS)
  215.                 pipe.next()
  216.                 STDINS[version] = pipe
  217.             pipe.send(fn)
  218.  
  219.  
  220. ################################################################
  221. def main():
  222.     usage = '%prog [-V [X.Y][-][A.B]] DIR_OR_FILE [-X REGEXPR]\n' + \
  223.      '       %prog -p PACKAGE'
  224.     parser = optparse.OptionParser(usage, version='%prog 0.9',
  225.                                    option_class=Option)
  226.     parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
  227.         help='turn verbose mode on')
  228.     parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
  229.         default=False, help='be quiet')
  230.     parser.add_option('-f', '--force', action='store_true', dest='force',
  231.         default=False, help='force rebuild even if timestamps are up-to-date')
  232.     parser.add_option('-O', action='store_true', dest='optimize',
  233.         default=False, help="byte-compile to .pyo files")
  234.     parser.add_option('-p', '--package',
  235.         help='specify Debian package name whose files should be bytecompiled')
  236.     parser.add_option('-V', type='version_range', dest='vrange',
  237.         help="""force private modules to be bytecompiled with Python version
  238. from given range, regardless of the default Python version in the system.
  239. If there are no other options, bytecompile all public modules for installed
  240. Python versions that match given range.
  241.  
  242. VERSION_RANGE examples: '2.5' (version 2.5 only), '2.5-' (version 2.5 or
  243. newer), '2.5-2.7' (version 2.5 or 2.6), '-3.0' (all supported 2.X versions)""")
  244.     parser.add_option('-X', '--exclude', action='append',
  245.         dest='regexpr', type='regexpr',
  246.         help='exclude items that match given REGEXPR. You may use this option \
  247. multiple times to build up a list of things to exclude.')
  248.  
  249.     (options, args) = parser.parse_args()
  250.  
  251.     if options.verbose or environ.get('PYCOMPILE_DEBUG') == '1':
  252.         log.setLevel(logging.DEBUG)
  253.         log.debug('argv: %s', sys.argv)
  254.         log.debug('options: %s', options)
  255.         log.debug('args: %s', args)
  256.     else:
  257.         log.setLevel(logging.WARN)
  258.  
  259.     if options.regexpr and not args:
  260.         parser.error('--exclude option works with private directories '
  261.             'only, please use /usr/share/python/bcep to specify '
  262.             'public modules to skip')
  263.  
  264.     if options.vrange and options.vrange[0] == options.vrange[1] and\
  265.        options.vrange != (None, None) and\
  266.        exists("/usr/bin/python%d.%d" % options.vrange[0]):
  267.         # specific version requested, use it even if it's not in SUPPORTED
  268.         versions = set(options.vrange[:1])
  269.     else:
  270.         versions = get_requested_versions(options.vrange, available=True)
  271.     if not versions:
  272.         log.error('Requested versions are not installed')
  273.         exit(3)
  274.  
  275.     if options.package and args:  # package's private directories
  276.         # get requested Python version
  277.         compile_versions = debsorted(versions)[:1]
  278.         log.debug('compile versions: %s', versions)
  279.  
  280.         pkg_files = tuple(get_package_files(options.package))
  281.         for item in args:
  282.             e_patterns = get_exclude_patterns(item, options.regexpr, \
  283.                                               compile_versions)
  284.             if not exists(item):
  285.                 log.warn('No such file or directory: %s', item)
  286.             else:
  287.                 log.debug('byte compiling %s using Python %s',
  288.                           item, compile_versions)
  289.                 files = get_private_files(pkg_files, item)
  290.                 compile(files, compile_versions, options.force,
  291.                         options.optimize, e_patterns)
  292.     elif options.package:  # package's public modules
  293.         # no need to limit versions here, it's either pyr mode or version is
  294.         # hardcoded in path / via -V option
  295.         e_patterns = get_exclude_patterns()
  296.         files = get_package_files(options.package)
  297.         files = get_public_files(files, versions)
  298.         compile(files, versions,
  299.                 options.force, options.optimize, e_patterns)
  300.     elif args:  # other directories/files (public ones mostly)
  301.         versions = debsorted(versions)[:1]
  302.         for item in args:
  303.             e_patterns = get_exclude_patterns(item, options.regexpr, versions)
  304.             files = get_directory_files(item)
  305.             compile(files, versions,
  306.                     options.force, options.optimize, e_patterns)
  307.     else:
  308.         parser.print_usage()
  309.         exit(1)
  310.  
  311.     # wait for all processes to finish
  312.     rv = 0
  313.     for process in WORKERS.itervalues():
  314.         process.communicate()
  315.         if process.returncode not in (None, 0):
  316.             rv = process.returncode
  317.     sys.exit(rv)
  318.  
  319. if __name__ == '__main__':
  320.     main()
  321.